package com.app.ytong.dialog;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.app.ytong.R;
import com.app.ytong.basis.Constants;
import com.app.ytong.bean.BaseInfoUpdateCache;
import com.app.ytong.bean.GoodsLevelListBean;
import com.app.ytong.bean.GoodsTimeListBean;
import com.app.ytong.bean.GoodsTypeListBean;
import com.app.ytong.bean.LoginBean;
import com.app.ytong.bean.TraderListBean;
import com.app.ytong.bean.UnitListBean;
import com.app.ytong.bean.UserListBean;
import com.app.ytong.greendao.GreenDaoUtils;
import com.flyco.dialog.widget.NormalDialog;
import com.qmuiteam.qmui.widget.QMUIProgressBar;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.ButterKnife;
import my.DialogUtils;
import my.LogUtil;
import my.StringUtil;
import my.http.MyHttpListener;
import my.http.MyHttpUtils;
import my.http.MyParams;


/**
 * @作者 fourfaith
 * @备注 新闻详情图片查看activity发、
 */
public class UpdateBaseInfoDialog extends NormalDialog {

	public static void toBaseInfoUpdateDialog(Activity mContext, BaseInfoUpdateCache updateInfo){
	    if(updateInfo == null){
	        updateInfo = new BaseInfoUpdateCache();
            updateInfo.setForceUpdate(true);
        }
		new UpdateBaseInfoDialog(mContext,updateInfo).show();
	}

//	public static void toBaseInfoUpdateDialog(Activity mContext){
//		new UpdateBaseInfoDialog(mContext).show();
//	}



	@BindView(R.id.progress_bar)
	QMUIProgressBar progress_bar;
	@BindView(R.id.text_message)
	TextView text_message;
	@BindView(R.id.text_percent)
	TextView text_percent;
	@BindView(R.id.text_total_current)
	TextView text_total_current;
	Activity mContext;

	int updatedCount = 0;
	int current_total = 100;
	String currentUpdate;

	BaseInfoUpdateCache updateInfo;


	public UpdateBaseInfoDialog(Activity context, BaseInfoUpdateCache dateInfo) {
		super(context);
		mContext = context;
		updateInfo = dateInfo;
		setCancelable(false);
		setCanceledOnTouchOutside(false);
	}

	@Override
	public View onCreateView() {
//        return super.onCreateView();
		View inflate = LayoutInflater.from(mContext).inflate(R.layout.user_update_baseinfo_dialog, null);
		ButterKnife.bind(this, inflate);
		widthScale(0.8f);
		return inflate;
	}

	@Override
	public void setUiBeforShow() {
		initViews();
		initData();
	}

	private void initViews() {

	}

	private void initData() {
		updateBaseInfoData();
	}

	@SuppressLint("StaticFieldLeak")
	public  void updateBaseInfoData() {
		new AsyncTask<String, Integer, String>() {
			@Override
			protected String doInBackground(String... strings) {

				if (updateInfo.isNeedUpdateGoodsType()) {
					currentUpdate = "正在下载货品种类数据";
					updatedCount = 0;
					current_total = updateInfo.getGoodsTypeCount();
					mHandler.sendEmptyMessage(MESSAGE_UPDATED_COUNT);
					getList(GreenDaoUtils.TYPE_GOODS);
				}

				if (updateInfo.isNeedUpdateGoodsLevel()) {
					currentUpdate = "正在下载货品等级数据";
					updatedCount = 0;
					current_total = updateInfo.getGoodsLevelCount();
					mHandler.sendEmptyMessage(MESSAGE_UPDATED_COUNT);
					getList(GreenDaoUtils.TYPE_LEVEL);
				}

				if (updateInfo.isNeedUpdateGoodsTime()) {
					currentUpdate = "正在下载货品年份数据";
					updatedCount = 0;
					current_total = updateInfo.getGoodsTimeCount();
					mHandler.sendEmptyMessage(MESSAGE_UPDATED_COUNT);
					getList(GreenDaoUtils.TYPE_TIME);
				}

				if (updateInfo.isNeedUpdateUnit()) {
					currentUpdate = "正在下载单位数据";
					updatedCount = 0;
					current_total = updateInfo.getUnitCountUpdated();
					mHandler.sendEmptyMessage(MESSAGE_UPDATED_COUNT);
					getList(GreenDaoUtils.TYPE_UNIT);
				}

				if (updateInfo.isNeedUpdateUser()) {
					currentUpdate = "正在下载用户数据";
					updatedCount = 0;
					current_total = updateInfo.getUserCountUpdated();
					mHandler.sendEmptyMessage(MESSAGE_UPDATED_COUNT);
					getList(GreenDaoUtils.TYPE_USER);
				}

				if (updateInfo.isNeedUpdateTrader()) {
					currentUpdate = "正在下载交易员数据";
					updatedCount = 0;
					current_total = updateInfo.getUserCountUpdated();
					mHandler.sendEmptyMessage(MESSAGE_UPDATED_COUNT);
					getList(GreenDaoUtils.TYPE_TRADER);
				}

				LogUtil.i("同步本地信息结束");
				return null;
			}

			@Override
			protected void onPostExecute(String s) {
				super.onPostExecute(s);
//				updateInfo.setLastCacheUpdateTime(new Date().getTime());
				updateInfo.save();
				currentUpdate = "下载信息完成";
				mHandler.sendEmptyMessage(MESSAGE_UPDATED_FINISH);
			}

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
			}
		}.execute("");

	}

	public void getList(String type) {
		MyParams params = null;
		switch (type) {
			case GreenDaoUtils.TYPE_GOODS:
				params = new MyParams();
				if(LoginBean.getInstance() == null || TextUtils.isEmpty(LoginBean.getInstance().getAid())){
					return;
				}
				params.put("aid", LoginBean.getInstance().getAid());
				MyHttpUtils.getExcute(Constants.URL_TYPES_SELECT_ALL, params, new MyHttpListener() {
							@Override
							public void onSuccess(int httpWhat, Object result) {
								if(mContext.isFinishing())return;
								GoodsTypeListBean goodsTypeListBean = (GoodsTypeListBean) result;
								GreenDaoUtils.goodsTypeInsertData(goodsTypeListBean, mCallBack);
								updateInfo.setUpdatedCountByMaptype(type,goodsTypeListBean.getList().size());
							}
							@Override
							public void onFailure(int httpWhat, Object result) {
								super.onFailure(httpWhat, result);
							}

							@Override
							public void onFinish(int httpWhat) {
							}

						},
						0, GoodsTypeListBean.class);
				break;

			case GreenDaoUtils.TYPE_LEVEL:
				params = new MyParams();
				if(LoginBean.getInstance() == null || TextUtils.isEmpty(LoginBean.getInstance().getAid())){
					return;
				}
				params.put("aid", LoginBean.getInstance().getAid());
				MyHttpUtils.getExcute(Constants.URL_LEVELS_SELECT_ALL, params, new MyHttpListener() {
							@Override
							public void onSuccess(int httpWhat, Object result) {
								if(mContext.isFinishing())return;
								GoodsLevelListBean goodsTypeListBean = (GoodsLevelListBean) result;
								GreenDaoUtils.goodsLevelInsertData(goodsTypeListBean, mCallBack);
								updateInfo.setUpdatedCountByMaptype(type,goodsTypeListBean.getList().size());
							}
							@Override
							public void onFailure(int httpWhat, Object result) {
								super.onFailure(httpWhat, result);
							}

							@Override
							public void onFinish(int httpWhat) {
							}

						},
						0, GoodsLevelListBean.class);
				break;

			case GreenDaoUtils.TYPE_TIME:
				params = new MyParams();
				if(LoginBean.getInstance() == null || TextUtils.isEmpty(LoginBean.getInstance().getAid())){
					return;
				}
				params.put("aid", LoginBean.getInstance().getAid());
				MyHttpUtils.getExcute(Constants.URL_YEVELS_SELECT_ALL, params, new MyHttpListener() {
							@Override
							public void onSuccess(int httpWhat, Object result) {
								if(mContext.isFinishing())return;
								GoodsTimeListBean goodsTimeListBean = (GoodsTimeListBean) result;
								GreenDaoUtils.goodsTimeInsertData(goodsTimeListBean, mCallBack);
								updateInfo.setUpdatedCountByMaptype(type,goodsTimeListBean.getList().size());
							}
							@Override
							public void onFailure(int httpWhat, Object result) {
								super.onFailure(httpWhat, result);
							}

							@Override
							public void onFinish(int httpWhat) {
							}

						},
						0, GoodsTimeListBean.class);
				break;

			case GreenDaoUtils.TYPE_USER:
				params = new MyParams();
				if(LoginBean.getInstance() == null || TextUtils.isEmpty(LoginBean.getInstance().getAid())){
					return;
				}
				params.put("aid", LoginBean.getInstance().getAid());
				params.put("uno", LoginBean.getInstance().getUno());
				MyHttpUtils.getExcute(Constants.URL_USER_SELECT_ALL, params, new MyHttpListener() {
							@Override
							public void onSuccess(int httpWhat, Object result) {
								if(mContext.isFinishing())return;
								UserListBean supplierListBean = (UserListBean) result;
								GreenDaoUtils.userBeanInsertData(supplierListBean, mCallBack);
								updateInfo.setUpdatedCountByMaptype(type,supplierListBean.getList().size());
							}
							@Override
							public void onFailure(int httpWhat, Object result) {
								super.onFailure(httpWhat, result);
							}

							@Override
							public void onFinish(int httpWhat) {
							}

						},
						0, UserListBean.class);
				break;
			case GreenDaoUtils.TYPE_UNIT:
				params = new MyParams();
				if(LoginBean.getInstance() == null || TextUtils.isEmpty(LoginBean.getInstance().getAid())){
					return;
				}
				params.put("aid", LoginBean.getInstance().getAid());
				MyHttpUtils.getExcute(Constants.URL_UNIT_SELECT_ALL, params, new MyHttpListener() {
							@Override
							public void onSuccess(int httpWhat, Object result) {
								if(mContext.isFinishing())return;
								UnitListBean unitListBean = (UnitListBean) result;
								GreenDaoUtils.unitInsertData(unitListBean, mCallBack);
								updateInfo.setUpdatedCountByMaptype(type,unitListBean.getList().size());
							}
							@Override
							public void onFailure(int httpWhat, Object result) {
								super.onFailure(httpWhat, result);
							}

							@Override
							public void onFinish(int httpWhat) {
							}

						},
						0, UnitListBean.class);
				break;

			case GreenDaoUtils.TYPE_TRADER:
				params = new MyParams();
				if(LoginBean.getInstance() == null || TextUtils.isEmpty(LoginBean.getInstance().getAid())){
					return;
				}
				params.put("aid", LoginBean.getInstance().getAid());
				MyHttpUtils.getExcute(Constants.URL_USER_SELECT_ALL_USER, params, new MyHttpListener() {
							@Override
							public void onSuccess(int httpWhat, Object result) {
								if(mContext.isFinishing())return;
								TraderListBean traderListBean = (TraderListBean) result;
								GreenDaoUtils.traderypeInsertData(traderListBean, mCallBack);
								updateInfo.setUpdatedCountByMaptype(type,traderListBean.getList().size());
							}
							@Override
							public void onFailure(int httpWhat, Object result) {
								super.onFailure(httpWhat, result);
							}

							@Override
							public void onFinish(int httpWhat) {
							}

						},
						0, TraderListBean.class);
				break;

		}
	}

	GreenDaoUtils.GreenDaoInserCallBack mCallBack = new GreenDaoUtils.GreenDaoInserCallBack() {
		@Override
		public void onDataInsert(int count) {
//			updatedCount++;
			updatedCount+= count;
			mHandler.sendEmptyMessage(MESSAGE_UPDATED_COUNT);
		}
	};

	public static final int MESSAGE_UPDATED_COUNT = 11;
	public static final int MESSAGE_UPDATED_FINISH = 12;
	public static final int MESSAGE_CONTACT_FAKE_PROGRESS = 13;
	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what){
				case MESSAGE_UPDATED_COUNT:
					updateProgressView();
					break;
				case MESSAGE_UPDATED_FINISH:
					StringBuilder builder = new StringBuilder();
					if(updateInfo.isUpdateSuccess()){
						if(updateInfo.isNeedUpdateGoodsType()){
							builder.append("货品种类共更新了").append(updateInfo.getGoodsTypeCountUpdated()).append("条 \n");
						}
						if(updateInfo.isNeedUpdateGoodsLevel()){
							builder.append("货品等级共更新了").append(updateInfo.getGoodsLevelCountUpdated()).append("条 \n");
						}
						if(updateInfo.isNeedUpdateGoodsTime()){
							builder.append("货品年份共更新了").append(updateInfo.getGoodsTimeCountUpdated()).append("条 \n");
						}
						if(updateInfo.isNeedUpdateUser()){
							builder.append("用户信息共更新了").append(updateInfo.getUserCountUpdated()).append("条 \n");
						}
						if(updateInfo.isNeedUpdateUnit()){
							builder.append("单位共更新了").append(updateInfo.getUnitCountUpdated()).append("条 \n");
						}
						if(updateInfo.isNeedUpdateTrader()){
							builder.append("交易员共更新了").append(updateInfo.getUnitCountUpdated()).append("条 \n");
						}

						EventBus.getDefault().post(new GreenDaoUtils.EventDateChange(GreenDaoUtils.EventDateChange.TYPE_ALL));
					}else {
						builder.append("更新失败");
					}
					DialogUtils.DialogOkMsg(mContext,builder.toString());
					dismiss();
					break;
			}

		}
	};



	void updateProgressView(){
//		LogUtil.i("updateProgressView------updatedCount-->"+updatedCount);
//		LogUtil.i("updateProgressView---current_total-->"+current_total);
		if(current_total == 0){
			current_total = 1000;
		}else {

			if(updatedCount >= current_total){
				updatedCount = current_total-1;
			}
		}
		progress_bar.setMaxValue(current_total);
		boolean animated = updatedCount > progress_bar.getProgress();
		progress_bar.setProgress(updatedCount,animated);
		text_message.setText(currentUpdate);
		text_total_current.setText(updatedCount+"/"+current_total);
		text_percent.setText(StringUtil.getPercent(updatedCount,current_total));
	}

}
